package com.lyfei.ydc.api;

import com.lyfei.ydc.domain.entity.Category;
import com.lyfei.ydc.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/category")
@Validated
public class CategoryController {
    private static final Logger logger = LoggerFactory.getLogger(CategoryController.class);

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/all")
    public Map<String, Object> queryAll() {
        List<Category> rootCategories = categoryService.getRootCategories();
        List<Category> subCategories = categoryService.getAllSubCategories();


        Category currentCategory = rootCategories.get(0);
        List<Category> currentSubList = null;
        if (currentCategory != null) {
            currentSubList = subCategories.stream().filter(subCategory -> subCategory.getParentId().equals(currentCategory.getId())
            ).collect(Collectors.toList());
        }

        Map<String, Object> result = new HashMap<>();
        result.put("currentCategory", currentCategory);
        result.put("currentSubList", currentSubList);
        result.put("roots", rootCategories);
        result.put("subList", subCategories);


        return result;
    }
}
